/*================================================================================================
 *                                       Courses Popularity (Course Profile Screen)
 *================================================================================================
 */


/* This function alows other user's to watch the current user selected courses */
function activateSharingSchedule(){	
	FB.api('/me', function(response) {
		window.bidit_globals.g_facebookUserID = response.id;


		//Saving user facebook id on server
		ajaxSendUserIDsToServer(window.bidit_globals.g_facebookUserID,window.bidit_globals.g_userID);

	});


}

function ajaxSendUserIDsToServer(facebookId,GoogleId){
	var saveIds = $.ajax({
		type: "GET",
		url: "/ajax/save-facebook-id/",
	%%	data: { 'university': window.bidit_globals.%%g_currUniversity,
			'facebookId': facebookId,
			'googleId': GoogleId},

			success: function(data){
				var sharingFlag = GoogleId + 's1';
				localStorage.isSharingSchedule = sharingFlag;
				updatePopularityTab(false);
			}
	});//ajax closed
}

function updatePopularityTab(isTabClicked){
	$('#popularityMainDivFacebook').hide();

	//if the user is not logged in
	if(window.bidit_globals.g_userID == ''){
		$('#popularityMainDiv').empty();
		$('#facebookInstructions').hide();
		$('#popularityMainDiv').append('<div style="text-align:center;">' + 'במסך זה תוכל לצפות במידע אודות מערכת השעות שבנו חבריך בפייסבוק' + '</div>');
		$('#popularityMainDiv').append('<div style="text-align:center;">' + 'bid-it - על מנת לצפות במידע זה, עליך ראשית להתחבר ל' + '</div>');
		$('#popularityMainDiv').append('<br>');
		$('#popularityMainDiv').append('<div id="loginFromPopularity" class="btn" role="button" style="text-align:center; margin-right: 55%; margin-left: 45%;">' + 'התחבר' + '</div>');
	}
	//if the user is logged in
	else{
		if(window.bidit_globals.g_facebookUserID == ''){
			var htmlLoginStr = $('#facebookLoginSpan').html();
			$('#popularityMainDiv').empty();
			$('#facebookInstructions').hide();

			var sharingFlag = window.bidit_globals.g_userID + 's1';
			//if the user has already approved sharing his schedule
			if(localStorage.isSharingSchedule == sharingFlag){
				$('#popularityMainDiv').append('<div style="text-align:center; direction: rtl;">' + 'רק עוד לחיצה אחת להתחברות דרך פייסבוק וכל המידע יהיה פה בשבילך:' + '</div>');
			}
			else{
				$('#popularityMainDiv').append('<div style="text-align:center;">' + '!רק עוד שלב אחד וזהו' + '</div>');
				$('#popularityMainDiv').append('<div style="text-align:center;"><p>' + 'כעת, על מנת שתוכל לצפות במערכת השעות שבנו חבריך' +'</p>' +
						'<p>' + 'עליך לאשר כי הנך מוכן לאפשר להם לצפות במערכת השעות שלך' + '</p>' +
				'</div>');
				$('#popularityMainDiv').append('<div style="text-align:center; direction: rtl;">' + 'לאישור לחץ על כפתור ההתחברות:' + '</div>');
			}

			$('#popularityMainDiv').append('<br>');
			$('#popularityMainDiv').append('<span id="facebookLoginSpan">' + htmlLoginStr + '</span>');
			$('#facebookLoginSpan').css({'margin-left':'45%', 'margin-right':'55%'});
		
		}
		else{
			if(window.bidit_globals.g_currCourseProfile != '-1'){
				$('#popularityMainDiv').empty();
				
				$('#popularityMainDiv').append('<span id="totalFriendsLikeThisCourse"></span><span id="userPic"></span>');
				
				getFacebookFriendsList(isTabClicked);

			}
		}

	}
	

}

function getFacebookFriendsList(isTabClicked){
	var courseProfileNum = window.bidit_globals.g_currCourseProfile;
	var departNum = courseProfileNum.substring(0,4);

	$('#totalFriendsLikeThisCourse').empty();
	$('#userPic').empty();
	$('#friendsColumn' + 1).empty();
	$('#friendsColumn' + 2).empty();
	$('#friendsColumn' + 3).empty();
	$('#friendsColumn' + 4).empty();
	$('#friendsColumn' + 5).empty();
	$('#friendsColumn' + 6).empty();
	
	FB.api('/me/friends', function(response) {
		var friendsArr = response.data;
		var ajaxFriendsArr = [];
	%%	ajaxFriendsArr.push(window.bidit_globals.%%g_currUniversity);
		ajaxFriendsArr.push(window.bidit_globals.g_currSemester+1);
		ajaxFriendsArr.push(departNum);
		ajaxFriendsArr.push(courseProfileNum);
		ajaxFriendsArr.push(friendsArr);
		
		if(isTabClicked){
			openFacebookBlockUI();
		}
		
		var friendsByCourse = $.ajax({
			type: "POST",
			url: "/ajax/get-friends-by-course/",
			dataType: 'json',
			data: JSON.stringify(ajaxFriendsArr),
			error: function(returnval){
				closeFacebookBlockUI();
				window.bidit_globals.g_facebookUserID = '';
				updatePopularityTab(isTabClicked);
			},
			success: function(ajaxResponse){
				if(isTabClicked){
					closeFacebookBlockUI();
				}
				
				showFacebookFriendsList(ajaxResponse.friendsList,ajaxResponse.totalCourseSelected);
				$('#popularityTab').removeClass('facebookTabBtnDisabled');
			}
		});//ajax closed




	});

}


function showFacebookFriendsList(friendsArr,totalSelectedNum){
	var totalFriendsLikesMessage = 'סה"כ בחרו בקורס';
	var friendsStr = 'חברים';
	var usersStr = 'משתמשים ומתוכם';
	var totalFriendsLikeThis = friendsArr.length;
	var userPicUrl = 'https://graph.facebook.com/' + window.bidit_globals.g_facebookUserID + '/picture';
	$('#totalFriendsLikeThisCourse').text(totalFriendsLikesMessage + ' ' + totalSelectedNum + ' ' + usersStr + ' ' + totalFriendsLikeThis + ' ' + friendsStr);
	$('#userPic').append('<img style="margin-bottom:1px; margin-top:-5px; width:30px; height:30px;" src="' + userPicUrl + '" class="pull-left img-rounded">');

	if(totalFriendsLikeThis > 0){
		$('#facebookInstructions').show();
	}
	else{
		$('#facebookInstructions').hide();
	}
	
	var columnNum = 1;
	for(var i=0; i < friendsArr.length; i++){
		var friendPicUrl = 'https://graph.facebook.com/' + friendsArr[i].id + '/picture';
		var columnClass = '';
		
		if(columnNum == 6 || columnNum == 5){
			columnClass = 'dropdown-right-column';
		}
		
		$('#friendsColumn' + columnNum).append('<div id="' + friendsArr[i].id + '" class="facebookFriend dropdown ' + columnClass + '" style=" width:60px; height:60px; margin-top:30px; padding: 20px 16px;">' +
				'<a class="dropdown-toggle" data-toggle="dropdown">' + 
				'<img style="width: 100%;" src="' + friendPicUrl + '" class="img-rounded">' + 
				'<p style="width: 100%; text-align:center; margin-top:1px; margin-bottom:5px;">' + friendsArr[i].name + '</p>' +
				'</a>' + 
				'<ul id="friendDropdown' + friendsArr[i].id  + '" class="dropdown-menu pre-scrollable" style="overflow-y:auto; max-height:100px;" role="menu" aria-labelledby="dropdownMenu"></ul>' + 
		'</div>');
		
		if(columnNum == 6){
			columnNum = 1;
		}
		else{
			columnNum = columnNum + 1;
		}
	}	
}

$('body').delegate('.facebookFriend','click',function(){
	var facebookId = $(this).attr('id');
	var friendCoursesAjax = $.ajax({
		type: "GET",
		url: "/ajax/get-friend-chosen-courses/",
		dataType: 'json',
	%%	data: { 'university': window.bidit_globals.%%g_currUniversity,
			'facebookId': facebookId },

			success: function(data){
				createFriendCoursesDropdown(data.friendCourses, facebookId);
			}
	});//ajax closed
});

function createFriendCoursesDropdown(friendCoursesDisplaySettings, facebookId){
	var currSemester = window.bidit_globals.g_currSemester;
	var currDisplaySettingsObj = friendCoursesDisplaySettings[currSemester];

	$('#friendDropdown' + facebookId).empty();
	$.each(currDisplaySettingsObj,function(){
		var courseNum = this.course_num;
		var courseName = this.course_name;
		
		var isChosen = this.cChosen;
		if(isChosen){
			$('#friendDropdown' + facebookId).append('<li id="friendCourse' + courseNum + '" class="facebookCourseDropdown" style="cursor:default;"><a id="facebookInfo" tabindex="-1">' + courseName + '</a></li>');
		}
	});
		
}

function openFacebookBlockUI(){

	$.blockUI({ message: $('#waitFacebook'), css: { 
		centerX: true,
		centerY: true,
		height: '50',
		width: '50',
		border: 'none', 
		padding: '15px',
		left: '48%',
		'-webkit-border-radius': '10px', 
		'-moz-border-radius': '10px', 
		opacity: .8, 
		color: '#fff',
	    background: 'none',
		'z-index': '2000'
	},
	overlayCSS:  {
		opacity:			0.6,
		cursor:				'wait',
		'z-index': '2000'
	}
	}); 

};

function closeFacebookBlockUI(){
	$.unblockUI();
}


